<?php
namespace app\common;

class ApiResponse extends \yii\base\BaseObject
{

    private string $_code;

    private string $_msg;

    private array $_data;

    /**
     * @var array|string[]
     */
    public static array $errCodes = [
        //基础的错误
        400 => '参数错误。',
        401 => '用户未登陆。',
        404 => '服务不存在。',
        500 => '未知错误。',
        501 => '服务器繁忙，请稍后重试。',//用于限流的时候，用于数据库异常
    ];

    /**
     * @return string
     */
    public function getCode(): string
    {
        return $this->_code;
    }

    /**
     * @param $code
     * @return void
     */
    public function setCode($code):void
    {
        $this->_code=$code;
    }

    /**
     * @return string
     */
    public function getMsg():string
    {
        return $this->_msg;
    }

    /**
     * @param string $msg
     */
    public function setMsg(string $msg): void
    {
        $this->_msg = $msg;
    }

    /**
     * @return array
     */
    public function getData(): array
    {
        return $this->_data;
    }

    /**
     * @param array $data
     */
    public function setData(array $data): void
    {
        $this->_data = $data;
    }


    /**
     * @param array $data
     * @return array
     */
    public function success(array $data=[]): array
    {

        $this->setCode('200');
        $this->setMsg('success');
        $this->setData($data);

        return $this->send();

    }

    /**
     * @param string $code
     * @param array $data
     * @return array
     */
    public function error(string $code='',array $data=[]): array
    {

        if(YII_DEBUG){
            $this->_code = $code;
            $this->_msg = "Debug Model.";
        }else {
            if ('' == $code || !isset(self::$errCodes[$code])) {
                $this->_code = 500;

            }else{
                $this->_code = $code;
            }
            $this->_msg = self::$errCodes[$this->_code];
        }

        if(null == $data || [] == $data){
            $this->_data = null;
        }else{
            $this->_data = $data;
        }
        return $this->send();

    }

    /**
     * @return array
     */
    public function send(): array
    {
        return [
            "statusCode"=>$this->_code,
            "msg" => $this->_msg,
            "returnData" => $this->_data
        ];
    }
}